package main

import (
	"fmt"
	"mock/gorm_start/ch01"
)

type User struct {
	Id        uint    `gorm:"column:user_id;type:int;primaryKey;not null;autoIncrement"`
	Name      *string `gorm:"column:user_name,type:varchar,not null;default:''"`
	CompanyId uint
	Company   Company `gorm:"foreignKey: CompanyRefer"` //重写关联外键
}

type Company struct {
	Id   uint
	Name *string
}

func (Company) TableName() string {
	return "my_company"
}

func main() {
	con, _ := ch01.NewCon()
	db := con.Db

	//db.AutoMigrate(&User{})

	n := "haha"
	u := User{Name: &n}
	create := db.Create(&u)
	fmt.Println(u.Id)
	println(create.RowsAffected)

	var name string
	name = "bobby"
	var companyName string
	companyName = "公司"
	db.Create(&User{
		Name: &name,
		Company: Company{ //正常添加company
			Name: &companyName,
		},
	})

	name = "bobby2"
	var company = Company{}
	db.Create(&User{
		Name: &name,
		Company: Company{ //还想使用之前的company,可以直接使用之前的companyId来解决
			Id: company.Id,
		},
	})

	db.Preload("Company").First(&User{})
}
